package com.czh.auth.application.interceptor;

import com.czh.auth.common.constants.AuthConstant;
import com.czh.auth.common.context.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import reactor.util.annotation.NonNull;

import java.util.Objects;

/**
 * 登录拦截器
 * 取出用户id 放入上下文
 * @author caozaihui
 * @version 1.0
 * @since 2024/9/9 10:42
 */

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response,@NonNull Object handler) {
        String loginId = request.getHeader(AuthConstant.USER_CONTEXT_ID);
        if (Objects.nonNull(loginId)){
            UserContext.set(AuthConstant.USER_CONTEXT_ID,loginId);
        }
        return true;
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,@NonNull Object handler, Exception ex) {
        UserContext.remove();
    }
}
